package com.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MailService {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender  javaMailSender;

    @Value("${spring.mail.username}")
    private String sendUsername;

    /**
     *
     * @param to         发送给谁(目的邮箱)
     */
    public void sendMail(String to)
    {
        //产生一个4位的验证码
        String  code = RandomUtil.randomString(4);

        //把产生的验证码写redis, 有效时间30分钟
        //set to  code EX 30*60
        redisTemplate.boundValueOps(to).set(code,30, TimeUnit.MINUTES);

        //发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("邮箱验证码");
        message.setFrom(sendUsername);
        message.setTo(to);
        message.setText("您的验证是:"+code);
        javaMailSender.send(message);



    }

    /**
     * 检查验证码是否正确
     * @param to  接收邮件的邮箱
     * @param code  验证码
     * @return  true正确
     */
    public boolean checkCode(String to, String code)
    {
         //从redis取出对应邮箱的验证码
         String redisCode = (String)redisTemplate.boundValueOps(to).get();
         boolean f =  code!=null && code.equalsIgnoreCase(redisCode);
         if (f)
         {
             //马上过期
             redisTemplate.boundValueOps(to).expire(0,TimeUnit.MILLISECONDS);
         }
         return f;
    }


}
